package hc.um.action;

import hc.um.Employee;
import hc.um.service.UserService;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ModifyUserServlet
 */
@WebServlet("/ModifyUserServlet")
public class ModifyUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private UserService userService = new UserService();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ModifyUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		try {
			this.modifyUser(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public void modifyUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException, SQLException {
		Employee employee = new Employee();
		
		String userid = null;
		userid = request.getParameter("userid");
		
		employee.setID(request.getParameter("userid"));
		employee.setLastName(request.getParameter("lname"));	
		employee.setFirstName(request.getParameter("fname"));
		employee.setBirthday(request.getParameter("birthday"));
		employee.setSex(request.getParameter("sexType"));
		employee.setPhone(request.getParameter("phone"));
		employee.setEmail(request.getParameter("email"));
		employee.setAddress(request.getParameter("address"));
		employee.setHospitalid(Integer.parseInt(request.getParameter("hospitalType")));
		employee.setRoleID(Integer.parseInt(request.getParameter("roleType")));
		
		if ( userService.updateUser(employee) == 1 )
		{
			response.getWriter().write(creatXmlTextModifyUser("Success","Modify the user successfully!",userid));
		} 
		else 
		{
			response.getWriter().write(creatXmlTextModifyUser("Fail","Modify User failed.",userid));
		}
	}
	
	public String creatXmlTextModifyUser(String result, String message, String userid) {
		String xmltext = null;

		xmltext = "<modifyuser><result>" + result + "</result><message>"
				+ message + "</message><userid>" + userid + "</userid></modifyuser>";
		System.out.println("xmltext="+xmltext);
		
		return xmltext;
	}		
}
